﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace Thksoft.UserCotrols
{
    public partial class CtrlWeekEditFunds3 : BaseControl
    {
        #region 重构代码

        private QS_PLANWEEKAPPLYBLL applyWeekBll = new QS_PLANWEEKAPPLYBLL();

        #endregion 重构代码

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string busId = Request.QueryString["BusinessId"].ToString();
                hidId.Value = busId;
                //ViewState["busId"] = busId.ToString();
                BindDt(busId);
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        public void BindDt(string busId)
        {
            QS_Business bModel = new Qs_BusinessBLL().GetBusinessById(Decimal.Parse(busId));

            lblTime.Text = bModel.Business_operator_date.ToShortDateString();

            lblUser.Text = new Sys_UserBLL().GetInfoById(bModel.Business_operator_Id.ToString()).USER_NAME;

            string sql = string.Format(@" select * from qs_planweekapply t where t.n_business_id=" + busId);

            DataTable dtYear = new BaseBLL().Query(sql);

            if (dtYear == null || dtYear.Rows.Count < 1)
            {
                Response.Write("<script>alert('【系统提示】该条数据有误，请与管理员联系');location.href='../Right.aspx';</script>");
                return;
            }

            string minday = DateTime.Parse(dtYear.Rows[0]["D_START"].ToString()).Day.ToString();
            string maxday = DateTime.Parse(dtYear.Rows[0]["D_END"].ToString()).Day.ToString();

            lblyear.Text = dtYear.Rows[0]["N_YEAR"].ToString() + "年" + dtYear.Rows[0]["N_MONTH"].ToString() + "月 " + minday + "-" + maxday + " 日";

            lblBzyj.Text = dtYear.Rows[0]["C_REAMRK"].ToString();

            lbldw.Text = new Sys_CompanyBLL().GetInfoById(dtYear.Rows[0]["N_COMPANY_ID"].ToString()).CMY_NAME;

            this.hidId.Value = dtYear.Rows[0]["N_MONTHAPP_ID"].ToString() + "@" + busId;

            DataTable dt = new QS_PLANWEEKAPPLYBLL().GetDataByBid(busId, lognUser.USER_NAME);

            HiddenField3.Value = dt.Rows[0]["n_weekapp_id"].ToString();

            gvMonthFunds.DataSource = dt;

            gvMonthFunds.DataBind();
        }

        protected void gvMonthFunds_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string type = ((Label)e.Row.FindControl("lbltype")).Text;
                var ifdetails = ((HiddenField)e.Row.FindControl("HiddenField1")).Value == "1" ? true : false;
                string sss = ((Label)e.Row.FindControl("lblProID")).Text;
                if (type == "0")
                {
                    e.Row.Attributes["style"] = "background-color:#B2D8FF;font-size: 14px";

                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;

                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;

                    // e.Row.Cells[2].Attributes["style"] = "font-size: 14px";
                }
                else if (type == "1")
                {
                    e.Row.Attributes["style"] = "background-color:#CCCCCC;font-size: 13px;";

                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;

                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;

                    //  e.Row.Cells[2].Attributes["style"] = "font-size: 13px";
                }
                else if (type == "2")
                {
                    //查询详情表的值
                    var applyId = Convert.ToInt32(HiddenField3.Value);

                    //  ((TextBox)e.Row.FindControl("txtNowMonth")).Text = applyWeekBll.GetMoneyByDetails(applyId, Convert.ToInt32(sss)).ToString();
                    if (ifdetails)
                    {
                        var code = ((HiddenField)e.Row.FindControl("HiddenField2")).Value;
                        ((TextBox)e.Row.FindControl("txtNowMonth")).Attributes.Add("onclick", "app1.ToDetails(" + HiddenField3.Value + ",3," + sss + ",'" + code + "')");
                        ((TextBox)e.Row.FindControl("txtNowMonth")).ReadOnly = true;
                    }
                }
            }
        }

        #region 求和 方法

        /// <summary>
        /// 求和
        /// </summary>
        private void Sum()
        {
            #region for循环求和

            DataTable dt = (DataTable)gvMonthFunds.DataSource;

            for (int i = 0; i < gvMonthFunds.Rows.Count; i++)
            {
                //0 主节点  1分节点  2子节点（可录入数据）
                string type = ((Label)gvMonthFunds.Rows[i].Cells[1].FindControl("lbltype")).Text;
                string pid = ((Label)gvMonthFunds.Rows[i].Cells[1].FindControl("lblProID")).Text;

                var ifdetails = ((HiddenField)gvMonthFunds.Rows[i].Cells[0].FindControl("HiddenField1")).Value == "1" ? true : false;

                if (type != "2" && type != "3")
                {
                    //求和
                    decimal heje = 0;
                    //该节点下所有子节点
                    DataTable dtchild = new QS_PROJECTBLL().SelectFor(" and  d.n_type = 2 ", pid, lognUser.USER_NAME);

                    for (int j = 0; j < dtchild.Rows.Count; j++)
                    {
                        for (int k = 0; k < gvMonthFunds.Rows.Count; k++)
                        {
                            string type2 = ((Label)gvMonthFunds.Rows[k].Cells[0].FindControl("lbltype")).Text;

                            string pid2 = ((Label)gvMonthFunds.Rows[k].Cells[0].FindControl("lblProID")).Text;

                            string reAmount = ((Label)gvMonthFunds.Rows[k].Cells[0].FindControl("lblReamount")).Text;

                            if (reAmount == "")
                            {
                                reAmount = "0";
                            }

                            //每个文本框求和
                            string je = ((TextBox)gvMonthFunds.Rows[k].Cells[6].FindControl("txtNowMonth")).Text.Trim();
                            string a = "";
                            if (je != "" && je != null)
                            {
                                a = FormulaCalculator.Eval(je).ToString();
                            }

                            if (type2 == "2" && dtchild.Rows[j]["n_proid"].ToString() == pid2)
                            {
                                //空值，表示默认取值
                                heje += Convert.ToDecimal(a == "" ? reAmount : a);
                                //heje += Convert.ToDecimal(((TextBox)gvMonthFunds.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim() == "" ? "0" : ((TextBox)gvMonthFunds.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim());
                            }
                        }
                    }

                    ((Label)gvMonthFunds.Rows[i].Cells[6].FindControl("lblMonthjh")).Text = heje.ToString();
                    ((TextBox)gvMonthFunds.Rows[i].Cells[6].FindControl("txtNowMonth")).Text = heje.ToString();
                }
                else
                {
                    decimal heje = 0;
                    string reAmount = ((Label)gvMonthFunds.Rows[i].Cells[0].FindControl("lblReamount")).Text;

                    if (reAmount == "")
                    {
                        reAmount = "0";
                    }

                    //每个文本框求和
                    string je = ((TextBox)gvMonthFunds.Rows[i].Cells[6].FindControl("txtNowMonth")).Text.Trim();
                    string a = "";
                    if (je != "" && je != null)
                    {
                        a = FormulaCalculator.Eval(je).ToString();
                    }
                    heje += Convert.ToDecimal(a == "" ? reAmount : a);

                    if (ifdetails)
                    {
                        if (heje != 0 || a == "0")
                        {
                            ((Label)gvMonthFunds.Rows[i].Cells[6].FindControl("lblMonthjh")).Text = heje.ToString();
                            ((TextBox)gvMonthFunds.Rows[i].Cells[6].FindControl("txtNowMonth")).Text = heje.ToString();
                        }
                        else
                        {
                            ((TextBox)gvMonthFunds.Rows[i].Cells[6].FindControl("txtNowMonth")).Text = "";
                        }
                    }
                    else
                    {
                        ((Label)gvMonthFunds.Rows[i].Cells[6].FindControl("lblMonthjh")).Text = heje.ToString();
                        ((TextBox)gvMonthFunds.Rows[i].Cells[6].FindControl("txtNowMonth")).Text = heje.ToString();
                    }
                }
            }

            #endregion for循环求和
        }

        #endregion 求和 方法

        protected void btnEdtSum_Click(object sender, EventArgs e)
        {
            Sum();
        }

        /// <summary>
        /// 重新加载数据(子表信息)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ReLoadClick(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvMonthFunds.Rows)
            {
                string proId = ((Label)row.FindControl("lblProID")).Text;
                string type = ((Label)row.FindControl("lbltype")).Text;
                var ifdetails = ((HiddenField)row.FindControl("HiddenField1")).Value == "1" ? true : false;
                if (type == "2" && ifdetails)
                {
                    //查询详情表的值
                    var applyId = Convert.ToInt32(HiddenField3.Value);
                    // ((TextBox)row.FindControl("txtNowMonth")).Text = applyWeekBll.GetMoneyByDetails(applyId, Convert.ToInt32(proId)).ToString();

                    decimal je = applyWeekBll.GetMoneyByDetails(applyId, Convert.ToInt32(proId));
                    if (je >= 0)
                    {
                        ((TextBox)row.FindControl("txtNowMonth")).Text = je.ToString();
                    }
                    var code = ((HiddenField)row.FindControl("HiddenField2")).Value;
                    ((TextBox)row.FindControl("txtNowMonth")).Attributes["onclick"] = "app1.ToDetails(" + HiddenField3.Value + ",3," + proId + ",'" + code + "')";
                    ((TextBox)row.FindControl("txtNowMonth")).ReadOnly = true;
                }
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            Sum();
            var list = new List<QS_PLANWEEK_DETAIL>();
            for (int i = 0; i < gvMonthFunds.Rows.Count; i++)
            {
                var ydModel = new QS_PLANWEEK_DETAIL();

                string id = ((Label)gvMonthFunds.Rows[i].Cells[0].FindControl("lblId")).Text;

                string xmmc = ((Label)gvMonthFunds.Rows[i].Cells[1].FindControl("txtProjectName")).Text;

                string je = ((TextBox)gvMonthFunds.Rows[i].Cells[2].FindControl("txtNowMonth")).Text;
                string aa = "";
                if (je != "" && je != null)
                {
                    aa = FormulaCalculator.Eval(je).ToString();
                }

                string bz = ((TextBox)gvMonthFunds.Rows[i].Cells[3].FindControl("txtremark")).Text;
                ydModel.N_WEEKDETAIL_ID = decimal.Parse(id);

                ydModel.N_AMOUNT = je == "" ? 0 : decimal.Parse(je);
                ydModel.N_AMOUNT2 = je == "" ? 0 : decimal.Parse(je);
                ydModel.C_REMARK2 = bz;

                ydModel.N_OPERATORID = lognUser.USER_ID;

                list.Add(ydModel);
            }

            int count = new QS_PLANWEEKAPPLYBLL().Updates(list, lognUser.USER_NAME);
            if (count == 0)
            {
                MessageBox.Show(Page, "修改失败！");
            }
        }
    }
}